from django.shortcuts import render, redirect
from web import models
from django import forms
from django.urls import reverse
from utils.bootstrap import BootStrapForm


# class LevelForm(BootStrapForm,forms.Form):
#     title = forms.CharField(
#         label='标题',
#         required=True,
#         widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入标题'})
#     )
#     percent = forms.CharField(
#         label='折扣',
#         required=True,
#         widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入折扣'}),
#         help_text="填入0-100的整数表示百分比，例如90,表示90%"
#     )

# def __init__(self, *args, **kwargs):
#     super().__init__(*args, **kwargs)
#
#     # {'title':对象,'percent':'对象'}
#     for name, field in self.fields.items():
#         field.widget.attrs['class'] = 'form-control'
#         field.widget.attrs['placeholder'] = "请输入{}".format(field.label)


class LevelModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.Level
        fields = ['title', 'percent']


# widgets = {
#     'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入标题'}),
#     'percent': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入折扣 '}),
# }


def level_list(request):
    # 数据库获取到数据
    # queryset = models.Level.objects.all() #这里不对 不是全部的而是已激活的如下
    queryset = models.Level.objects.filter(active=1)
    return render(request, 'level_list.html', {"queryset": queryset})


def level_add(request):
    if request.method == "GET":
        form = LevelModelForm()
        return render(request, 'form.html', {"form": form})

    form = LevelModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {"form": form})

    # {'title':'标题是啥','折扣':'打多少折'}
    # print(form.cleaned_data)
    # models.Level.objects.create(**form.cleaned_data)
    form.save()
    # form.instance.percent = 15
    # return redirect(reverse('level_list'))
    # return redirect('/level/list/')
    from utils.link import filter_reverse
    return redirect(filter_reverse(request, "/level/list/"))

def level_edit(request, pk):
    level_object = models.Level.objects.filter(id=pk, active=1).first()
    if request.method == "GET":
        form = LevelModelForm(instance=level_object)
        return render(request, 'form.html', {"form": form})

    # 获取数据 + 校验
    form = LevelModelForm(data=request.POST, instance=level_object)
    if not form.is_valid():
        return render(request, 'form.html', {"form": form})
    # 根据ID将用户提交的数据更新
    # models.Level.objects.filter(id=pk).update(title=form.cleaned_data['title'], percent=form.cleaned_data['percent'])
    form.save()
    return redirect(reverse('level_list'))


def level_delete(request, pk):
    exists = models.Customer.objects.filter(level_id=pk).exists()
    if not exists:
        models.Level.objects.filter(id=pk).update(active=0)
    return redirect(reverse('level_list'))
